package com.xiaojiang.controller;

import cn.dev33.satoken.util.SaResult;
import com.xiaojiang.dto.RepairEmailDto;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * 功能：
 * 作者：小江
 * 日期：2024年10月26日
 */
@RestController
@RequestMapping("/api")
public class RepairEmailController {

    @Autowired
    private JavaMailSender mailSender; // 正确的注入方式

    @PostMapping("/sendEmail")
    public SaResult sendEmail(@Valid @RequestBody RepairEmailDto repairEmailDto) {
        // 将 UTC 时间转换为北京时间（东八区）
        ZonedDateTime beijingTime = repairEmailDto.getDateTime().atZoneSameInstant(ZoneId.of("Asia/Shanghai"));

        // 构建邮件内容
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo("447839355@qq.com"); // 收件人邮箱地址
        message.setFrom("2725508505@qq.com"); // 发件人邮箱地址
        message.setSubject("设备报修通知"); // 邮件主题
        message.setText(
                "设备类型：" + repairEmailDto.getDeviceType() + "\n" +
                        "区域：" + repairEmailDto.getRegion() + "\n" +
                        "申报时间：" + beijingTime.toLocalDateTime() + "\n" +
                        "描述：" + repairEmailDto.getDesc()
        );
        try {
            // 发送邮件
            mailSender.send(message);
            return SaResult.ok("邮件发送成功！");
        } catch (Exception e) {
            return SaResult.error("邮件发送失败：" + e.getMessage());
        }
    }
}
